package tables

import (
	"peilian-api/app/global/variable"
	"time"
)

//客户信息表

type Agent struct {
	Model
	ConnectPeople    string     `gorm:"type:varchar(20);not null;comment:联系人姓名"`
	ConnectPhone     string     `gorm:"type:varchar(20);not null;comment:联系电话"`
	Counterpart      string     `gorm:"type:varchar(20);not null;comment:对接人"`
	CounterpartPhone string     `gorm:"type:varchar(20);not null;comment:对接人联系电话"`
	ServiceStartTime time.Time  `gorm:"comment:服务开始时间"`
	ServiceEndTime   time.Time  `gorm:"comment:服务开始时间"`
	SurplusTime      int64      `gorm:"type:int(11);default:0;comment:服务到期剩余"`
	Type             string     `gorm:"type:varchar(10);not null;comment:客户类型,school/company/other"`
	AgentName        string     `gorm:"type:varchar(255);not null;comment:客户名称"`
	Email            string     `gorm:"type:varchar(255);not null;comment:客户邮箱"`
	School           string     `gorm:"type:varchar(255);not null;comment:学校名称"`
	Usage            uint       `gorm:"type:int(11);default:0;comment:该客户用量"`
	FirstConstitute  Constitute `gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;comment:客户构成要素中的第一级要素(即学校)"`

	AppId             string `gorm:"type:varchar(40);comment:app_id"`
	AppSecret         string `gorm:"type:varchar(40);comment:app_secret"`
	IsSync            bool   `gorm:"default:false;comment:是否开启训练记录同步"`
	Concurrent        int    `gorm:"type:int(4);default:0;comment:支持的并发数量"`
	AppletsConcurrent int    `gorm:"type:int;default:0;comment:小程序一起使用的数量"`
	AppletsUseDays    int    `gorm:"type:int;default:0;comment:小程序端使用的天数"`
}

func (Agent) TableName() string {
	return "agent"
}

// 获取所有的agent信息
func (*Agent) GetAgentList() ([]Agent, error) {
	var agts []Agent
	if d := variable.DB.MySQL.Find(&agts); d.Error != nil {
		return agts, d.Error
	}
	return agts, nil
}

// 添加agent信息
func (*Agent) AddAgent(aif Agent) (Agent, error) {
	if d := variable.DB.MySQL.Save(&aif); d.Error != nil {
		return aif, d.Error
	}
	return aif, nil
}

// 根据id更新信息
func (*Agent) UpdateAgentById(upd map[string]interface{}, id int64) (int64, error) {
	d := variable.DB.MySQL.Model(Agent{}).Where("id = ?", id).Updates(upd).Limit(1)
	if d.Error != nil {
		return d.RowsAffected, d.Error
	}
	return d.RowsAffected, nil
}

// 根据条件查询信息
func (*Agent) GetAgentByWhere(where map[string]interface{}, whereStr string) ([]Agent, error) {
	var ats []Agent
	if len(whereStr) == 0 {
		if d := variable.DB.MySQL.Model(Agent{}).Where(where).Where(whereStr).Find(&ats); d.Error != nil {
			return ats, d.Error
		}
	} else {
		if d := variable.DB.MySQL.Model(Agent{}).Where(where).Where(whereStr).Find(&ats); d.Error != nil {
			return ats, d.Error
		}
	}
	return ats, nil
}

// 根据条件删除信息
func (*Agent) DeleteAgentById(id uint) error {
	d := variable.DB.MySQL.Model(Agent{}).Delete("id = ?", id).Limit(1)
	return d.Error
}

// 根据条件获取信息
func GetAgentById(id uint) (Agent, error) {
	agent := Agent{}
	d := variable.DB.MySQL.Model(Agent{}).Where("id = ?", id).First(&agent)
	return agent, d.Error
}
